<?php

namespace App\Exceptions;

use App\Exceptions\Code\ErrorCode;
use App\Exceptions\JsonResponse\JsonResponseException;
use App\Exceptions\JsonResponse\JsonResponseLastException;
use App\Exceptions\JsonResponse\ResponseValidationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Throwable;


class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception
     * @param \Throwable $exception
     * @throws \Throwable
     */
    public function report(\Throwable $exception)
    {
        parent::report($exception);
    }

    public function render($request, \Throwable $e)
    {
        if ($request->expectsJson()) {
            $e = $this->convertExceptionOfJson($e);
        }
        return parent::render($request, $e);
    }

    protected function convertExceptionOfJson(Throwable $e)
    {
        if ($e instanceof JsonResponseException) {
            return $e;
        }
        if ($e instanceof AuthenticationException) {
            return (new JsonResponseLastException(JsonResponseException::getErrorMessage(ErrorCode::AUTHENTICATION_ERROR), ErrorCode::AUTHENTICATION_ERROR, $e));
        }
        if ($e instanceof ValidationException) {
            return (new ResponseValidationException("", ErrorCode::VALIDATION_FAILED, $e));
        }
        if ($e instanceof UnauthorizedHttpException) {
            return (new JsonResponseException("", ErrorCode::TOKEN_MISSING));
        }
        if ($e instanceof NotFoundHttpException) {
            return (new JsonResponseException("", ErrorCode::NOT_FOUND_HTTP));
        }
        return (new JsonResponseLastException("", ErrorCode::SERVICE_ERROR, $e));
    }

}
